package com.example.app.yidu.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;

import com.example.app.yidu.R;
import com.example.app.yidu.activity.fragment.FbFragment;
import com.example.app.yidu.activity.fragment.MdFragment;
import com.example.app.yidu.activity.fragment.TjFragment;
import java.io.ByteArrayOutputStream;
import java.io.File;


public class MainActivity extends AppCompatActivity implements RadioGroup.OnCheckedChangeListener {
    private FrameLayout ma_fl;
    private RadioGroup ma_rg;
    private FragmentManager ma_fa;
    private TjFragment tjf;
    private FbFragment fbf;
    private MdFragment mdf;
    private DrawerLayout main_dl;
    private NavigationView main_dl_ngv;
    private ImageView ngv_head_iv;
    private LinearLayout ngv_head;
    private Toolbar toolbar;
    private FragmentTransaction ft;
    private static final int ALBUM_REQUEST_CODE = 1,CAMERA_REQUEST_CODE=2,
    CROP_REQUEST_CODE=4;
    private static final String IMAGE_UNSPECIFIED = "image/*";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        initListener();
    }



    /**
     * 侧边栏监听
     */
    private void initListener() {
        main_dl_ngv.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem item) {
                switch (item.getItemId()) {
                    case R.id.menu_sc:
                        startActivity(new Intent(MainActivity.this,SouCangActivity.class));
                        break;
                    case R.id.menu_movie:
                        startActivity(new Intent(MainActivity.this,MovieActivity.class));
                        break;
                    case R.id.menu_xx:
                        startActivity(new Intent(MainActivity.this,XiaoXiActivity.class));
                        break;
                    case R.id.menu_fk:
                        startActivity(new Intent(MainActivity.this,FankuiActivity.class));
                        break;
                    case R.id.menu_sz:
                        startActivity(new Intent(MainActivity.this,SetActivity.class));
                        break;
                }
                item.setChecked(true);// 改变item选中状态
                //关闭DrawerLayout
                main_dl.closeDrawers();
                return true;
            }
        });
        ngv_head_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setIcon();
            }
        });
    }

    private void initView() {
        ma_fl= (FrameLayout) findViewById(R.id.ma_fl);
        ma_rg= (RadioGroup) findViewById(R.id.ma_rg);
        ma_rg.setOnCheckedChangeListener(this);
        ma_fa=getSupportFragmentManager();
        main_dl_ngv= (NavigationView) findViewById(R.id.main_dl_ngv);
        main_dl= (DrawerLayout) findViewById(R.id.main_dl);
        //因为侧拉中的头像id不能直接获取，故而需要间接先通过NavigationView获取head部分，在进行iv获取
        //又因为是动态添加，所以xml中的head就必须删除，不然会出现两个头
        ngv_head = (LinearLayout) main_dl_ngv.inflateHeaderView(R.layout.header_layout);
        ngv_head_iv = (ImageView) ngv_head.findViewById(R.id.ngv_head_iv);
        toolbar= (Toolbar) findViewById(R.id.toolbar);
        //实现侧边栏切换按钮动画//
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, main_dl, toolbar, R.string.open, R.string.close);
        main_dl.setDrawerListener(toggle);
        toggle.syncState();
        //关闭实现侧边栏切换按钮动画//
        //设置侧拉栏图片显示自己本身状态颜色
        main_dl_ngv.setItemIconTintList(null);
        //设置默认选中
        ma_rg.check(R.id.rg_tj);
    }

    /**
     * 底部button切换相应监听
     * @param group
     * @param checkedId
     */

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        ft = ma_fa.beginTransaction();
        switch (checkedId) {
            case R.id.rg_tj:
                initFragment1();
                break;
            case R.id.rg_fb:
                initFragment2();
                break;
            case R.id.rg_md:
                initFragment3();
                break;
        }

    }
    //显示第一个fragment
    private void initFragment1(){
        //开启事务，fragment的控制是由事务来实现的
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        //初始化fragment并添加到事务中，如果为null就new一个
        if(tjf == null){
            tjf = new TjFragment();
            transaction.add(R.id.ma_fl, tjf);
        }
        //隐藏所有fragment
        hideFragment(transaction);
        //显示需要显示的fragment
        transaction.show(tjf);
        transaction.commit();
    }

    //显示第二个fragment
    private void initFragment2(){
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        if(fbf == null){
            fbf = new FbFragment();
            transaction.add(R.id.ma_fl,fbf);
        }
        hideFragment(transaction);
        transaction.show(fbf);
        transaction.commit();
    }

    //显示第三个fragment
    private void initFragment3(){
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

        if(mdf == null){
            mdf = new MdFragment();
            transaction.add(R.id.ma_fl,mdf);
        }
        hideFragment(transaction);
        transaction.show(mdf);
        transaction.commit();
    }

    /**
     * 隐藏所有fragment
     * @param transaction
     */
    private void hideFragment(FragmentTransaction transaction){
        if(tjf != null){
            transaction.hide(tjf);
        }
        if(fbf != null){
            transaction.hide(fbf);
        }
        if(mdf != null){
            transaction.hide(mdf);
        }
    }
    /**
     * 开始裁剪
     *
     * @param uri
     */
    private void startCrop(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");//调用Android系统自带的一个图片剪裁页面,
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");//进行修剪
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 300);
        intent.putExtra("outputY", 500);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_REQUEST_CODE);
    }
    /**
     * 打开相册设置个人头像
     */
    private void setIcon() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
        startActivityForResult(intent, ALBUM_REQUEST_CODE);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case ALBUM_REQUEST_CODE:
                if (data == null) {
                    return;
                }
                startCrop(data.getData());
                break;
            case CAMERA_REQUEST_CODE:
                File picture = new File(Environment.getExternalStorageDirectory()
                        + "/temp.jpg");
                startCrop(Uri.fromFile(picture));
                break;
            case CROP_REQUEST_CODE:
                if (data == null) {
                    // TODO 如果之前以后有设置过显示之前设置的图片 否则显示默认的图片
                    return;
                }
                Bundle extras = data.getExtras();
                if (extras != null) {
                    Bitmap photo = extras.getParcelable("data");
                    ByteArrayOutputStream stream = new ByteArrayOutputStream();
                    photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0-100)压缩文件
                    //此处可以把Bitmap保存到sd卡中，具体请看：http://www.cnblogs.com/linjiqin/archive/2011/12/28/2304940.html
                    ngv_head_iv.setImageBitmap(photo); //把图片显示在ImageView控件上
                }
                break;
            default:
                break;
        }
    }
    private Fragment cufg=new TjFragment();
}
